package CelestialWeb;

import CelestialDataAccess.Product;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import CelestialDataAccess.*;
import CelestialDataStructures.*;

import java.util.UUID;
import java.util.List;
import java.util.Collection;
import java.util.ArrayList;

//information is separated into order, orderItem, product
//so as to compress files as file transfer is slower than file processing

public class ViewOrderHistoryServlet extends HttpServlet {
    private WriteXMLError m_WriteError = new WriteXMLError();
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String strCusID = request.getParameter("customerID");

        response.setContentType("text/xml");
        response.setHeader("Cache-control", "no-cache");
        PrintWriter pw = response.getWriter();

        if(strCusID==null){
            m_WriteError.writeSingleError(1, "No Customer ID is supplied", pw);
            return;
        }
		  
		  CustomersDataAccess cusAccess = new CustomersDataAccess();
		  Customer curCust;
        ProductsDataAccess daProducts = new ProductsDataAccess();
        Product prod;
		  OrdersDataAccess orderAccess = new OrdersDataAccess();
		  List<Order> orderList;
		  int temp;	//helps double conversion
		  
		  try{
		  		curCust = cusAccess.getCustomerByID( Integer.parseInt(strCusID) );
		  }
		  catch(DataAccessException ex){
		  		m_WriteError.writeSingleError(16384, ex.getMessage(), pw);
				return;
		  }
		  
		  //if no orders found write an empty xml and return
//rewrite to empty after database working
		  if(curCust==null){
		  		pw.write("<Details>");
				
		  		pw.write("<CustomerID>100002</CustomerID>");
		  		pw.write("<FirstName>Xin Yu</FirstName>");
		  		pw.write("<LastName>Zhang</LastName>");
				
				pw.write("<tblOrders>");
				pw.write("<Order>");
				pw.write("<OrderID>FEBE1B7F-33A0-4B90-94BA-07E50C103EA4</OrderID>");
				pw.write("<OrderDate>2010-03-06 12:00:00.000</OrderDate>");
				pw.write("<DeliveryDate>_</DeliveryDate>");
				pw.write("<Status>0</Status>");
				pw.write("<NetAmount>450.00</NetAmount>");
				pw.write("</Order>");
				pw.write("</tblOrders>");
				
				pw.write("<tblOrderItems>");
				pw.write("<OrderID>FEBE1B7F-33A0-4B90-94BA-07E50C103EA4</OrderID>");
				pw.write("<ProductID>pro00290</ProductID>");
				pw.write("<Quantity>3</Quantity>");
				pw.write("<UnitPrice>150.00</UnitPrice>");
				pw.write("<PriceOverride>0</PriceOverride>");
				pw.write("</tblOrderItems>");
				
				pw.write("<tblProductInventory>");
				pw.write("<Product>");
				pw.write("<ProductID>pro00290</ProductID>");
				pw.write("<ItemName>Product 190</ItemName>");
				pw.write("</Product>");
				pw.write("</tblProductInventory>");
				
		  		pw.write("</Details>");
		  }

//start of xml write		  
		  else{
			  pw.write("<Details>");		  
			  pw.write("<CustomerID>"+ curCust.getCustomerID() +"</CustomerID>");
			  pw.write("<FirstName>"+ curCust.getFirstName() +"</FirstName>");
			  pw.write("<LastName>"+ curCust.getLastName() +"</LastName>");
			  
			  try{
			  		orderList = new ArrayList<Order>();
					orderAccess.getOrdersByCustomerID( curCust.getCustomerID() , orderList );
			  }catch(DataAccessException ex){
			  		m_WriteError.writeSingleError(16384, ex.getMessage(), pw);
					return;
			  }
			if(!orderList.isEmpty() && orderList!=null){
				pw.write("<tblOrders>");
				for(Order curOrder:orderList){
					  pw.write("<Order>");
					  pw.write("<OrderID>");
					  pw.write(curOrder.getOrderID().toString());			  
					  pw.write("</OrderID>");
					  pw.write("<OrderDate>");
					  pw.write(curOrder.getOrderDate().toString());
					  pw.write("</OrderDate>");
					  pw.write("<DeliveryDate>");
					  pw.write(curOrder.getDispatchDate().toString());
					  pw.write("</DeliveryDate>");
					  pw.write("<Status>");
					  pw.write("" + curOrder.getStatus());
					  pw.write("</Status>");
					  pw.write("<NetAmount>");
					  temp = (int)(curOrder.getTotalAmount()* 100);
					  pw.write("" + (temp/100.0) );
					  pw.write("</NetAmount>");		
					  pw.write("</Order>");					  
				}	  
				pw.write("</tblOrders>");	

//access list of order items
				//prevents duplication
				Collection<OrderItem> check = new ArrayList<OrderItem>();
				for(Order curOrder:orderList){			
					  Collection<OrderItem> orderItemList = curOrder.getOrderItems();
					  for(OrderItem ordItem : orderItemList){
					  		  if(!check.contains(ordItem)){
								  pw.write("<tblOrderItems>");
								  pw.write("<OrderID>");
								  pw.write(ordItem.m_uidOrderItemID.toString());
								  pw.write("</OrderID>");
								  pw.write("<ProductID>");
								  pw.write(ordItem.m_strProductID);
								  pw.write("</ProductID>");
								  pw.write("<Quantity>");
								  pw.write("" + ordItem.m_iQuantity);
								  pw.write("</Quantity>");
								  pw.write("<UnitPrice>");
								  temp = (int)(ordItem.m_dblUnitPrice * 100);
								  pw.write("" + temp/100.0);
								  pw.write("</UnitPrice>");
								  pw.write("<PriceOverride>");
								  pw.write("" + ordItem.m_bPriceOverride);
								  pw.write("</PriceOverride>");
								  pw.write("</tblOrderItems>");
								  
								  check.add(ordItem);
								}
						}
				}
				
//write for product
				//prevents duplication
				Collection<Product> pCheck = new ArrayList<Product>();
				
				pw.write("<tblProductInventory>");
				for(Order curOrder:orderList){			
					  	Collection<OrderItem> orderItemList = curOrder.getOrderItems();
						for(OrderItem ordItem : orderItemList){
							try{
								prod = daProducts.getProductByID(ordItem.m_uidOrderItemID.toString());
							}catch(DataAccessException ex){
								m_WriteError.writeSingleError(16384, ex.getMessage(), pw);
								return;
							}
							if(! pCheck.contains(prod) ){
								pw.write("<Product>");
								pw.write("<ProductID>");
								pw.write(prod.getProductID());
								pw.write("</ProductID>");
								pw.write("<ItemName>");
								pw.write(prod.getProductName());
								pw.write("</ItemName>");
								pw.write("</Product>");
							}
						}
				}

				pw.write("</tblProductInventory>");
			}
			else{
				pw.write("<tblOrders>");
				pw.write("<Order>");
				pw.write("<OrderID>_</OrderID>");
				pw.write("<OrderDate>_</OrderDate>");
				pw.write("<DeliveryDate>_</DeliveryDate>");
				pw.write("<Status>1</Status>");
				pw.write("<NetAmount>_</NetAmount>");
				pw.write("</Order>");
				pw.write("</tblOrders>");
				
				pw.write("<tblOrderItems>");
				pw.write("<OrderID>_</OrderID>");
				pw.write("<ProductID>_</ProductID>");
				pw.write("<Quantity>_</Quantity>");
				pw.write("<UnitPrice>_</UnitPrice>");
				pw.write("<PriceOverride>_</PriceOverride>");
				pw.write("</tblOrderItems>");
				
				pw.write("<tblProductInventory>");
				pw.write("<Product>");
				pw.write("<ProductID>_</ProductID>");
				pw.write("<ItemName>_</ItemName>");
				pw.write("</Product>");
				pw.write("</tblProductInventory>");
			}

		  	pw.write("</Details>");
		}
			//end of all writing of xml
		pw.close();
	}
		  
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
